#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: zhangZW
@file: module.py
@time: 2022/09/02
@des: api接口基础文件，由其他的api用例继承，并重写 send 方法实现自动化测试。
"""

from run_tests import logger
from config import RunConfig
from globaltest import Global

class Module:
    value = {
        'method': None,
        'scheme': 'https',
        'ip': None,
        'port': 443,
        'path': None,
        'params': None,
        'data': None,
        'headers': None,
    }

    def __init__(self, session=None, base_ip=None, mysql=None,cookies=None):
        self.result_json = None
        self.session = session
        self.base_ip = base_ip
        self.mysql = mysql
        self.cookies = cookies
        self.res_cookies = None
        self.code = None
        self.result_text = None
        self.result_content = None
        RunConfig.API_RESULT_CODE = None
        RunConfig.API_RESULT = None

    def send(self):
        global _res
        va = lambda x: self.value.get(x, None)
        if not va('ip'):
            self.value['ip'] = self.base_ip
        if va('method') is None or va('ip') is None:
            raise ValueError('接口必要条件不全，请检查-method or ip.')
        if va('scheme') == 'http':
            self.value['port'] = 80
        if va('path') is None:
            self.value['path'] = '/'
        try:
            _res = self.session.request(
                method=va('method'),
                url=va('scheme') + '://' + va('ip') + ':' + str(va('port')) + va('path'),
                params=va('params'),
                data=va('data'),
                headers=va('headers'),
                timeout=50,
                cookies=self.cookies
            )
            logger.info(f"{va('method')}：{va('scheme') + '://' + va('ip') + ':' + str(va('port')) + va('path')}")
            self.res_cookies = _res.cookies
            self.code = _res.status_code
            self.result_text = _res.text
            self.result_content = _res.content
            RunConfig.API_RESULT_CODE = self.code
            try:
                RunConfig.API_RESULT = self.result_json()
            except Exception:
                RunConfig.API_RESULT = self.result_text
        except Exception as e:
            logger.error(f"{va('method')}：{va('scheme') + '://' + va('ip') + ':' + str(va('port')) + va('path')}"
                         f"--请求失败--{e}")

    def result_json(self):
        self.result_json = _res.json()

    @staticmethod
    def output(key, _value):
        Global.API_global.update({key: _value})

    @staticmethod
    def input(key):
        return Global.API_global.get(key, None)


if __name__ == '__main__':
    pass
